package org.yxj.changethemeapp

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


/**
 * activity基类
 *
 * @author yxj on 2024/6/24
 */
open class BaseActivity : AppCompatActivity() {

    var appMainBackground = 0
    var appMenuText = 0
    var appMenuIconTint = 0
    var appTimelapseStartDrawable = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initTheme()
        initAttr()
    }


    /**
     * 初始化主题
     *
     */
    private fun initTheme() {
        Toast.makeText(this, "当前模式=" + isDarkModeStatus(), Toast.LENGTH_LONG).show()
        /**
         * 是否跟随系统
         */
        if (isDarkModeStatus()) {
            setTheme(R.style.AppDarkTheme)
        } else {
            setTheme(R.style.AppWhiteTheme)
        }
        setAndroidNativeLightStatusBar(isDarkModeStatus())
        submergedBar()
    }



    /**
     * 检查当前系统是否已开启暗黑模式
     */
    private fun isDarkModeStatus(): Boolean {
//        val mode: Int = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
//        return mode == Configuration.UI_MODE_NIGHT_YES
        return CacheThemeManager.isDarkModeStatus(this)
    }




    private fun setAndroidNativeLightStatusBar(dark: Boolean) {
        val decor: View = window.decorView
        if (dark) { //暗黑 设置状态栏为白色
            decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        } else { //设置状态栏为黑色
            decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    }


    /**
     * 沉嵌式 状态栏
     *
     * @param context
     */
    open fun submergedBar() {
        if (Build.VERSION.SDK_INT in 19..20) {
            //透明状态栏
           window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        } else if (Build.VERSION.SDK_INT >= 21) {
            window.statusBarColor = Color.TRANSPARENT
        }
    }



    /**
     * 获取颜色属性
     */
    private fun initAttr() {
        val array = obtainStyledAttributes(
            intArrayOf(
                R.attr.AppMainBackground,
                R.attr.AppMenuText,
                R.attr.AppMenuIconTint,
                R.attr.AppTimelapseStartDrawable
            )
        )

        appMainBackground = array.getColor(array.getIndex(0), Color.BLACK)
        appMenuText = array.getColor(array.getIndex(1), Color.BLACK)
        appMenuIconTint = array.getColor(array.getIndex(2), Color.BLACK)
        appTimelapseStartDrawable = array.getResourceId(array.getIndex(3), 0)

        array.recycle()
    }
}